package com.feature50.clarity;

import java.io.File;
import java.io.InputStream;

public class ResourceLoader {
    public enum Type { Form, Stylesheet }

    private static ResourceLoader instance;

    /**
     * Converts a string representing a FormUI key to path following the same convention as the Java package structure.
     * I.e., "com.feature50.app.SomeFormUI" is converted to "com/feature50/app/SomeFormUI", where the forward-slash
     * is the path character on the current OS.
     *
     * @param resourceName
     * @return
     */
    public String getPackageAwareResourceName(String resourceName) {
        return resourceName.replaceAll("\\.", File.separator);
    }

    public ClassLoader getClassLoader() {
        return getClass().getClassLoader();
    }

    public InputStream getInputStream(Type type, String name, String extension) {
        String dir;
        switch (type) {
            case Form:
                dir = "forms";
                break;
            case Stylesheet:
                dir = "css";
                break;
            default:
                throw new IllegalArgumentException(String.format("Type %1$s unknown", type));
        }

        return getInputStream(dir, name, extension);
    }

    public InputStream getInputStream(String resourcesDirName, String name, String extension) {
        if (!extension.startsWith(".")) extension = "." + extension;
        String dir = resourcesDirName + File.separatorChar + getPackageAwareResourceName(name) + extension;
        return getClassLoader().getResourceAsStream(dir);
    }

    public static synchronized ResourceLoader getInstance() {
        if (instance == null) {
            instance = new ResourceLoader();
        }

        return instance;
    }
}
